/**
*      author: Y_Yao
*      created: 2025-01-24 19:40:00
**/

#include<bits/stdc++.h>

#define int LL
using namespace std;
using LL = long long;
const LL LLINF = 1e18;
const int INF = 0x3f3f3f3f;
const int N = 10000 + 7;
int T[N],C[N],P[N],dp[N];
string s;
int f1,f2,f3,f4;
int sh,sm,eh,em,n;
int sumt;

void put()
{
    getline(cin,s);
    for(int i = 0;i < s.size();i++)
    {
        if(s[i] == ':')
        {
            if(f1 == 0) f1 = i;
            else f3 = i;
        }
        if(s[i] == ' ')
        {
            if(f3 == 0) f2 = i;
            else f4 = i;
        }
    }

    sh = stoi(s.substr(0,f1));
    sm = stoi(s.substr(f1 + 1,2));
    eh = stoi(s.substr(f2 + 1,f3));
    em = stoi(s.substr(f3 + 1,2));
    n = stoi(s.substr(f4 + 1));

    sumt = (eh - sh) * 60 + (em - sm);
}

void solve()
{
    put();
    for(int i = 1;i <= n;i++)
    {
        cin >> T[i] >> C[i] >> P[i];
    }

    for(int i = 1;i <= n;i++)
    {
        if(P[i] == 0)//完全
        {
            for(int j = T[i];j <= sumt;j++)
            {
                dp[j] = max(dp[j],dp[j-T[i]] + C[i]);
            }
        }
        else//多重
        {
            for(int k = 1;k <= P[i];k++)
            {
                for(int j = sumt;j >= T[i];j--)
                {
                    dp[j] = max(dp[j],dp[j-T[i]] + C[i]);
                }
            }
        }
    }

    cout << dp[sumt] << endl;
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    int t = 1;
    //cin >> t;
    while(t--)
    {
        solve();
    }
    return 0;
}